/**
* @description: 1020. 飞地的数量
* @author hewei
* @date 2022/10/5 15:04
* @version 1.0
*/

public class NumEnclaves {

    public static void main(String[] args) {
        int[][] nums = {{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}};
        System.out.println(new NumEnclaves().numEnclaves(nums));
    }

    int count;
    int[][] grid;
    int[][] step = {{0, -1}, {1, 0}, {-1, 0}, {0, 1}};
    public int numEnclaves(int[][] grid) {
        count = 0;
        this.grid = grid;
        int ans = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1 && !process(i, j)) ans += count;
                count = 0;
            }
        }
        return ans;
    }

    public boolean process(int x, int y) {
        ++count;
        grid[x][y] = 0;
        boolean res = false;
        int m = grid.length;
        int n = grid[0].length;
        if (x == 0 || x == m - 1 || y == 0 || y == n - 1) res = true;
        for (int[] ints : step) {
            int i = x + ints[0];
            int j = y + ints[1];
            if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1) continue;
            res = (process(i, j) || res);
        }
        return res;
    }
}
